package br.com.caesarhoppen.cryptography;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
 * Aes encrypter baseado no codigo do DesEncrypter. Foi criada uma interface comum aos dois para facilitar o trabalho.
 * @author crfhoppen
 *
 */
public class AesEncrypter implements CryptoEncrypter {
	private static final String PBKDF2_WITH_HMAC_SHA1 = "PBKDF2WithHmacSHA1";
	private static final String AES_CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";
	
    private byte[] buf = new byte[1024];

    byte[] iv = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
    private byte[] salt = {
        (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
        (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
    };

    private Cipher ecipher;
    private Cipher dcipher;

    public AesEncrypter(String password) {
    	 try {
    		 SecretKeyFactory factory = SecretKeyFactory.getInstance(PBKDF2_WITH_HMAC_SHA1);
    		 KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1024, 128);
    		 SecretKey tmp = factory.generateSecret(spec);
    		 SecretKey key = new SecretKeySpec(tmp.getEncoded(), "AES");

    		 // cria o encrypter
    		 ecipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
    		 ecipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
             
    		 // cria o decrypter
             dcipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
             dcipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
         } catch (Exception e) {
        	 e.printStackTrace();
        	 System.exit(0);
         }
    }

    public void encrypt(InputStream in, OutputStream out) {
        try {
            out = new CipherOutputStream(out, ecipher);
            int numRead = 0;
            
            while ((numRead = in.read(buf)) >= 0) {
                out.write(buf, 0, numRead);
            }
        } catch (IOException e) {
        	e.printStackTrace();
        } finally {
        	try {
				out.close();
			} catch (IOException e) {}
        }
    }

    public void decrypt(InputStream in, OutputStream out) {
        try {
            in = new CipherInputStream(in, dcipher);

            int numRead = 0;
            while ((numRead = in.read(buf)) >= 0) {
                out.write(buf, 0, numRead);
            }
        } catch (IOException e) {
        	e.printStackTrace();
        } finally {
        	try {
				out.close();
			} catch (IOException e) {}
        }
    }
}

